<?php

namespace EthanZ\LaravelExt\Middleware;

use EthanZ\LaravelExt\Log\Log;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Throwable;

/**
 * Sql|info日志记录
 */
class SysLog
{

    /*********  日志写入失败首先查看redis是否正常  *********/


    /**
     * 处理传入请求
     *
     * @param Request $request 参数.
     * @param Closure $next    继续执行.
     *
     * @return mixed
     */
    public function handle(Request $request, Closure $next): mixed
    {
        if (Str::contains(env('LOG_LEVEL', 'error,slow'), ['sql', 'slow'])) {
            // 开启sql执行记录.
            DB::enableQueryLog();
        }

        return $next($request);
    }


    /**
     * 响应后操作.
     *
     * @throws Throwable
     */
    public function terminate(): void
    {
        // 记录信息日志.
        Log::info();
        if (Str::contains(env('LOG_LEVEL', 'error,slow'), ['sql', 'slow'])) {
            // 获取该请求的sql执行记录.
            $query = DB::getQueryLog();
            // 记录sql日志.
            if ($query) {
                Log::slow($query);
                Log::sql($query);
            }
        }
    }
}
